<?php
/**
 * 余额逻辑层
 * @author 王勇程 <laughskydragon@qq.com>
 */

namespace app\common\logic;

class Balance extends LogicBase
{
    /**
     * 增加用户余额
     */
    public function addBalance($userId, $amount, $type = 'recharge', $remark = '')
    {
        try {
            if (!$userId || $amount <= 0) {
                return [RESULT_ERROR, '参数错误'];
            }
            
            // 获取用户信息
            $user = $this->modelUser->getInfo(['id' => $userId]);
            if (!$user) {
                return [RESULT_ERROR, '用户不存在'];
            }
            
            // 更新用户余额
            $result = $this->modelUser->updateInfo(['id' => $userId], [
                'available_amount' => $user['available_amount'] + $amount,
                'update_time' => time()
            ]);
            
            if ($result) {
                // 记录余额变动
                $this->addBalanceRecord($userId, $amount, $type, $remark);
                return ['balance' => $user['available_amount'] + $amount];
            }
            
            return [RESULT_ERROR, '余额更新失败'];
            
        } catch (\Exception $e) {
            \think\facade\Log::error('增加用户余额失败：' . $e->getMessage());
            return [RESULT_ERROR, '操作失败'];
        }
    }
    
    /**
     * 减少用户余额
     */
    public function reduceBalance($userId, $amount, $type = 'consume', $remark = '')
    {
        try {
            if (!$userId || $amount <= 0) {
                return [RESULT_ERROR, '参数错误'];
            }
            
            // 获取用户信息
            $user = $this->modelUser->getInfo(['id' => $userId]);
            if (!$user) {
                return [RESULT_ERROR, '用户不存在'];
            }
            
            // 检查余额是否足够
            if ($user['available_amount'] < $amount) {
                return [RESULT_ERROR, '余额不足'];
            }
            
            // 更新用户余额
            $result = $this->modelUser->updateInfo(['id' => $userId], [
                'available_amount' => $user['available_amount'] - $amount,
                'update_time' => time()
            ]);
            
            if ($result) {
                // 记录余额变动
                $this->addBalanceRecord($userId, -$amount, $type, $remark);
                return ['balance' => $user['available_amount'] - $amount];
            }
            
            return [RESULT_ERROR, '余额更新失败'];
            
        } catch (\Exception $e) {
            \think\facade\Log::error('减少用户余额失败：' . $e->getMessage());
            return [RESULT_ERROR, '操作失败'];
        }
    }
    
    /**
     * 添加余额变动记录
     */
    public function addBalanceRecord($userId, $amount, $type, $remark = '', $extraData = [])
    {
        try {
            $recordData = [
                'user_id' => $userId,
                'amount' => $amount,
                'type' => $type,
                'remark' => $remark,
                'extra_data' => json_encode($extraData),
                'create_time' => time(),
                'update_time' => time()
            ];
            
            // 这里假设有一个余额记录模型，如果没有可以创建或使用其他方式记录
            // return $this->modelBalanceRecord->updateInfo([], $recordData);
            
            // 临时记录到日志
            \think\facade\Log::info('余额变动记录', $recordData);
            
            return true;
            
        } catch (\Exception $e) {
            \think\facade\Log::error('添加余额记录失败：' . $e->getMessage());
            return false;
        }
    }
    
    /**
     * 获取用户余额
     */
    public function getUserBalance($userId)
    {
        try {
            if (!$userId) {
                return [RESULT_ERROR, '用户ID不能为空'];
            }
            
            $user = $this->modelUser->getInfo(['id' => $userId], 'available_amount,total_earnings');
            if (!$user) {
                return [RESULT_ERROR, '用户不存在'];
            }
            
            return [
                'available_amount' => $user['available_amount'],
                'total_earnings' => $user['total_earnings']
            ];
            
        } catch (\Exception $e) {
            \think\facade\Log::error('获取用户余额失败：' . $e->getMessage());
            return [RESULT_ERROR, '获取失败'];
        }
    }
    
    /**
     * 获取余额变动记录
     */
    public function getBalanceRecords($data = [])
    {
        try {
            $userId = $data['user_id'] ?? 0;
            $type = $data['type'] ?? '';
            $page = $data['page'] ?? 1;
            $limit = $data['limit'] ?? 20;
            
            if (!$userId) {
                return [RESULT_ERROR, '用户ID不能为空'];
            }
            
            // 这里需要根据实际的余额记录表来实现
            // 临时返回空数据
            return [
                'data' => [],
                'total' => 0,
                'page' => $page,
                'limit' => $limit
            ];
            
        } catch (\Exception $e) {
            \think\facade\Log::error('获取余额记录失败：' . $e->getMessage());
            return [RESULT_ERROR, '获取失败'];
        }
    }
}